package org.rafal.springframework.controller;

import java.util.Date;

import javax.inject.Inject;
import javax.validation.Valid;

import org.rafal.springframework.domain.App_User;
import org.rafal.springframework.service.App_UserService;
import org.rafal.springframework.service.FileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping(value = "/users")
public class UserController {
	private static final Logger logger = LoggerFactory
			.getLogger(UserController.class);
	private App_UserService app_UserService;

	private FileService fileService;

	@Inject
	public void setFileService(FileService fileService) {
		this.fileService = fileService;
	}

	@Inject
	public UserController(App_UserService app_UserService) {
		this.app_UserService = app_UserService;
	}

	/**
	 * Handles users request
	 * 
	 * @param model
	 *            all users from database
	 * @return view name
	 */
	@RequestMapping(method = RequestMethod.GET)
	public String showAllUsers(Model model) {
		logger.info("Showing all users!");
		model.addAttribute("users", app_UserService.findAll());
		return "users";
	}

	/**
	 * Handles
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET, params = "new")
	public String createUser(Model model) {
		model.addAttribute("user", new App_User());
		logger.info("Going to users edit....");
		return "users/edit";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String addUser(
			@Valid @ModelAttribute(value = "user") App_User user,
			BindingResult bindingResult,
			@ModelAttribute(value = "image") @RequestParam(value = "image", required = false) MultipartFile image) {

		if (bindingResult.hasErrors()) {
			logger.info("Error binding has got "
					+ bindingResult.getErrorCount());
			return "users/edit";
		}
		user.setJoinDate(new Date());
		app_UserService.save(user);
		try {
			if (!image.isEmpty()) {
				logger.info("Image is not Empty. Validating file ");
				fileService.validateImage(image);
				fileService.saveImage(
						"/users/" + user.getId() + "/" + user.getId() + ".jpg",
						image);
			}

		} catch (Exception e) {
			return "users/edit";
		}

		return "redirect:/users/user/" + user.getId();
	}

	@RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
	public String showUserProfile(@PathVariable Long id, Model model) {

		App_User user = app_UserService.findById(id);
		logger.info("Showing profile for user name " + user.getName());
		model.addAttribute("user", user);
		return "userProfile";
	}

}
